from django.db import models
from django.core.validators import MinValueValidator, MaxValueValidator
from django.forms.models import model_to_dict

from enum import Enum


def get_shipping_container_validators():
    return [
        MinValueValidator(1),
        MaxValueValidator(2e5)
    ]


class ShippingContainer(models.Model):
    name = models.TextField(
        unique=True,
        help_text='运输柜名称，如"20GP"')

    height = models.FloatField(
        validators=get_shipping_container_validators(),
        help_text='运输柜的高度')

    width = models.FloatField(
        validators=get_shipping_container_validators(),
        help_text='运输柜的宽度')

    length = models.FloatField(
        validators=get_shipping_container_validators(),
        help_text='运输柜的长度')

    created = models.DateTimeField(auto_now_add=True)


class TaskStatus(Enum):
    IDLE = 'idle'
    SUBMITTED = 'submitted'
    RUNNING = 'running'
    ERROR = 'error'
    FINISHED = 'finished'

    @classmethod
    def choices(cls):
        return tuple((i.value, i.name) for i in cls)


class Task(models.Model):
    name = models.TextField(help_text='计算任务昵称')
    status = models.TextField(choices=TaskStatus.choices(), default=TaskStatus.IDLE.value, help_text='运行时状态')
    config = models.JSONField(help_text='算法参数', null=True, blank=True)
    input_dataset = models.JSONField(help_text='待计算数据', null=True, blank=True)
    result_dataset = models.JSONField(help_text='计算结果数据', null=True, blank=True)

    creator = models.ForeignKey(
        'common.User',  # due to circular reference
        related_name='taks',
        on_delete=models.CASCADE,
        null=True, blank=True,
        help_text='创建该任务的用户')
    created_at = models.DateTimeField(auto_now_add=True, help_text='创建时间戳')
    submitted_at = models.DateTimeField(null=True, blank=True, help_text='递交时间戳')
    finished_at = models.DateTimeField(null=True, blank=True, help_text='结束时间戳')

    def to_json(self) -> dict:
        return model_to_dict(self)
